//
//  GetUserBasicInfoService.m
//  ERP
//
//  Created by QA on 16/4/29.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "GetUserBasicInfoService.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"
#import "ServiceConnect.h"
#import "ModuleAuthorityEntity+CoreDataClass.h"

@interface GetUserBasicInfoService()

@end

static GetUserBasicInfoService *sharedMenuService = nil;
@implementation GetUserBasicInfoService

+ (GetUserBasicInfoService*)sharedService
{
    @synchronized(self){
        if (sharedMenuService == nil){
            sharedMenuService = [[self alloc] init];
        }
    }
    return sharedMenuService;
}

- (void)startQueryService
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    if (!userInfo) {
        //保存数据失败回执
        [self sendNotificationCenter:@"登录已过期，请重新登录"];
        return;
    }
    
    //获取权限信息表数据
    [self startQueryUserMenuServiceNew];
}

- (void)stopMenuAuthorityService
{
    //删除模块
    NSArray *persons = [ModuleAuthorityEntity MR_findAll];
    for(ModuleAuthorityEntity *model in persons) [model MR_deleteEntity];
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

- (void)dealloc
{
    sharedMenuService = nil;
}

#pragma make - Send Notification

- (void)sendNotificationCenter:(id)anObject
{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    NSNotification *broadcastMessage = [NSNotification notificationWithName:GetUserBasicInfoServiceKey object:anObject];
    [notificationCenter postNotification:broadcastMessage];
}

#pragma make -
#pragma make - 获取网络权限表(WebServer)

- (void)startQueryUserMenuServiceNew
{
    //判断用户是否登录
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    
    //获取消息信息表数据
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"MobileMenu" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            [self networkDataProcess:result.resultArray];
        } else {
            //保存数据失败回执
            [self sendNotificationCenter:@"您未分配使用权限，请联系相关负责人开通"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===服务器繁忙==%@",error);
        //[self sendNotificationCenter:@"服务器繁忙，请重新尝试连接"];
        //延迟5秒，重新查询数据
        __block GetUserBasicInfoService *weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf startQueryService];
        });
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===网络异常==%@",error);
        //[self sendNotificationCenter:@"网络异常，请检查网络是否正常"];
        //延迟5秒，重新查询数据
        __block GetUserBasicInfoService *weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf startQueryService];
        });
    }];
}

- (void)networkDataProcess:(NSArray*)userInfoArray
{
    //删除数据
    [self stopMenuAuthorityService];
    
    //获取菜单权限
    for(NSDictionary *temp in userInfoArray){
        ModuleAuthorityEntity *person = [ModuleAuthorityEntity MR_createEntity];
        person.data = [temp objectFormatStringForKey:@"data" defaults:@""];
        person.descripter = [temp objectFormatStringForKey:@"descripter" defaults:@""];
        person.icon = [temp objectFormatStringForKey:@"icon" defaults:@""];
        person.nativeCode = [temp objectFormatStringForKey:@"nativeCode" defaults:@""];
        person.id = [temp objectFormatIntegerNumberForKey:@"id"];
        person.order = [temp objectFormatIntegerNumberForKey:@"orders"];
        person.parentId = [temp objectFormatIntegerNumberForKey:@"parentId"];
        person.title = [temp objectFormatStringForKey:@"title" defaults:@""];
        person.codeType = [temp objectFormatIntegerNumberForKey:@"codeType"];
        person.module = [temp objectFormatIntegerNumberForKey:@"module"];
        person.moduleType = [temp objectFormatIntegerNumberForKey:@"moduleType"];
        person.webCode = [temp objectFormatStringForKey:@"webCode" defaults:@""];
        person.webModuleH = [temp objectFormatIntegerNumberForKey:@"webModuleH"];
        person.webModuleUrl = [temp objectFormatStringForKey:@"webModuleUrl" defaults:@""];
        person.isPermissions = [temp objectFormatIntegerNumberForKey:@"isPermissions"];
        person.permissionsMark = [temp objectFormatStringForKey:@"permissionsMark" defaults:@""];
    }
    
    //保存数据成功并回执
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    [self sendNotificationCenter:nil];
}

@end
